package io.plus.interactive.utils;

import java.nio.ByteBuffer;

public class ByteBufferUtils {

    /**
     * 组合两个bytebuffer，把可读部分的组合成一个新的bytebuffer
     */
    public static ByteBuffer composite(ByteBuffer byteBuffer1, ByteBuffer byteBuffer2) {
        int capacity = byteBuffer1.remaining() + byteBuffer2.remaining();
        ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);

        byteBuffer.put(byteBuffer1);
        byteBuffer.put(byteBuffer2);

        byteBuffer.position(0);
        byteBuffer.limit(byteBuffer.capacity());
        return byteBuffer;
    }


    /**
     * @param src        本方法不会改变position等指针变量
     * @param startindex 从0开始
     */
    /**
     * @param src 本方法不会改变position等指针变量
     */
    public static ByteBuffer copy(ByteBuffer src) {

        return copy(src, src.position(), src.limit());
    }

    public static ByteBuffer copy(ByteBuffer src, int startindex, int endindex) {
        int size = endindex - startindex;
        int initPosition = src.position();
        int initLimit = src.limit();

        src.position(startindex);
        src.limit(endindex);
        ByteBuffer ret = ByteBuffer.allocate(size);
        ret.put(src);
        ret.flip();

        src.position(initPosition);
        src.limit(initLimit);
        return ret;
    }


}
